﻿using MediatR;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.ErrorCodeEnum;
using SqlSugar;
using T.Common.Domain.Common;

namespace RedDragon.RBAC.API.Application.Common.Permission
{
    public class DeletelPermissionHandler : IRequestHandler<DeletePermissionCommand, Result>
    {
        private readonly ISqlSugarClient db;
        /// <summary>
        /// 权限仓储
        /// </summary>
        public readonly IBaseRepository<Permissions> permissionsRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<DeletelPermissionHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="permissionsRepository"></param>
        /// <param name="logger"></param>
        public DeletelPermissionHandler(ISqlSugarClient db, IBaseRepository<Permissions> permissionsRepository, ILogger<DeletelPermissionHandler> logger)
        {
            this.db = db;
            this.permissionsRepository = permissionsRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 权限删除
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(DeletePermissionCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var list = await (await permissionsRepository.GetAll()).Where(d => d.PermissionId == request.PermissionId).FirstAsync();
                if (list != null)
                {
                    list.IsDelete = 1;
                }
                var res = permissionsRepository.Update(list);
                result.Code = (int)CommonErrorCode.Success;
                result.Msg = "权限删除成功";
            }
            catch (Exception ex)
            {
                logger.LogError("权限删除异常");
                result.Msg = "权限删除异常";
            }
            return result;
        }
    }
}
